package com.bite.forum.interceptor;

import com.bite.forum.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${forum.login.url}")
    private String loginUrl;
    /**
     * 前置处理
     * @return true：放行，false：拦截
     * @throws Exception 未登录
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取session 对象
        HttpSession session = request.getSession(false);
        // 判断session是否有效
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            // 用户为已登录状，校验通过
            return true;
        }
        // 校验URL是否正确
        if (!loginUrl.startsWith("/")) {
            loginUrl = "/" + loginUrl;
        }
        // 校验不通过, 跳转到登录页面
        response.sendRedirect(loginUrl);
        // 中断流程
        return false;
    }
    /*@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            return true;
        }

        // 动态拼接上下文路径
        String redirectUrl = request.getContextPath() + loginUrl;
        response.sendRedirect(redirectUrl);
        return false;
    }*/
}

